// pages/groupdetails/groupdetails.js
const app = getApp()
var drawing = false; /*避免多次点击保存按钮*/
Page({
  /**
   * 页面的初始数据
   */
  data: {
    current: 0,
    isRemove: false,
    query: '',
    news_id: '',
    groupId: '',
    groupImage: [],
    groupName: '',
    groupDescription: '',
    groupLeader: '',
    leaderCompany: '',
    leaderJob: '',
    leaderImage: '',
    otherData: [],
    searchData: [],
    searchBox: false, //搜索盒子
    isSearch: true, //为搜索状态
    is_ingroup: '', //（当前用户是否是组员 1：是；0：否）
    is_leader: '', //（当前用户是否是组长 1：是；0：否）
    is_add: '', //（是否可邀请他人加入 1：是；0：否）
    deviceWidth: '',
    deviceHeight: '',
    qrcodeUrl: '../../img/tou.jpg',
  },
  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value);

    var otherData = this.data.otherData,
      values = e.detail.value;
    for (var i = 0, lenI = otherData.length; i < lenI; ++i) {
      otherData[i].checked = false;

      for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (otherData[i].value == values[j]) {
          otherData[i].checked = true;
          break;
        }
      }
    }

    this.setData({
      otherData: otherData
    });
  },
  /**
   * 获取搜索字段
   */
  getQuery(e) {
    // console.log(e);
    var that = this
    that.setData({
      query: e.detail.value
    })
    if (e.detail.value == '' && that.data.query == '') {
      that.setData({
        isSearch: true,
        searchBox: false
      })
    }
  },
  /**
   * 搜索名片
   */
  query: function (e) {
    var that = this;
    wx.request({
      url: app.globalData.url + 'Group/search',
      data: {
        openid: wx.getStorageSync('openid'),
        news_id: that.data.news_id,
        keywords: that.data.query
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        if (res.data.status === 1) {
          that.setData({
            searchData: res.data.data,
            searchBox: true,
            isSearch: false
          })
          console.log(that.data.searchData);

        } else if (res.data.status === 0) {
          wx.showToast({
            title: res.data.msg,
            // icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log(options.news);
    that.setData({
      news_id: options.news
    })
    wx.getSystemInfo({
      success(res) {
        console.log(res);
        console.log(res.windowWidth);
        console.log(res.windowHeight);
        that.setData({
          deviceWidth: res.windowWidth,
          deviceHeight: res.windowHeight
        })
      }
    })
    // 初始化名片组信息
    wx.request({
      url: app.globalData.url + 'Group/detail',
      data: {
        openid: wx.getStorageSync('openid'),
        news_id: options.news,
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        if (res.data.status === 1) {
          that.setData({
            groupId: res.data.data.detail.id,
            is_ingroup: res.data.data.detail.is_ingroup,
            is_add: res.data.data.detail.is_add,
            groupImage: res.data.data.detail.image,
            groupName: res.data.data.detail.title,
            groupDescription: res.data.data.detail.description,
            is_leader: res.data.data.my_card.is_leader,
            groupLeader: res.data.data.my_card.username,
            leaderCompany: res.data.data.my_card.company,
            leaderJob: res.data.data.my_card.job,
            leaderImage: res.data.data.my_card.image,
            otherData: res.data.data.other_cards,
          })
        } else if (res.data.status === 0) {
          wx.showToast({
            title: res.data.msg,
            // icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
    wx.request({
      url: app.globalData.url + 'Index/smallCode', //域名省略
      data: {
        openid: wx.getStorageSync('openid'),
        page: "",
        scene: `${that.data.news_id}`,
        width: 300
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'GET',
      // dataType: 'json',
      success: function (res) {
        console.log(res);
        res.data = '../../img/tou.jpg'
        that.setData({
          qrcodeUrl: res.data //服务器小程序码地址
        })
      },
      fail: function () {},
      complete: options.complete || function () {}
    })

  },
  /**
   * 移除名片
   */

  /**
   * 保存图片
   */
  savePoster: function (e) {
    var that = this;
    var current = this.data.current;
    //获取相册授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() { //这里是用户同意授权后的回调
              that.drawPoster(current);
            },
            fail() { //这里是用户拒绝授权后的回调
              wx.showModal({
                title: '提示',
                content: '若不打开授权，则无法将图片保存在相册中！',
                showCancel: true,
                cancelText: '去授权',
                cancelColor: '#000000',
                confirmText: '暂不授权',
                confirmColor: '#3CC51F',
                success: function (res) {
                  if (res) {
                    wx.openSetting({
                      //调起客户端小程序设置界面，返回用户设置的操作结果。
                    })
                  } else {
                    // console.log('用户点击取消')
                  }
                }
              })
            }
          })
        } else { //用户已经授权过了 
          that.drawPoster(current);
        }
      }
    })
  },
  /* 绘制海报*/
  drawPoster: function (current) {
    if (drawing) {
      wx.showToast({
        title: '绘制中……',
        icon: 'loading',
        duration: 3000
      })
    } else {
      drawing = true;
      // loading 
      // 根据swiper当前所在滑块的 index判断绘制对应海报
      switch (current) {
        case 0:
          this.drawPosterOne()
          break;
        case 1:
          this.drawPosterTwo()
          break;
        case 2:
          this.drawPosterThree()
          break;
      }
    }

  },
  /*一张产品图*/
  drawPosterOne: function () {
    var that = this;
    var ctx = wx.createCanvasContext('canvasposter');
    // const ctx = wx.createCanvasContext('myCanvas');
    var imgPath = '../../img/buy.png';
    var imgUserPath = '../../img/tou.jpg';
    var code = that.data.qrcodeUrl;
    //绘制图像到画布 x y width height
    ctx.drawImage(imgPath, 0, 0, (that.data.deviceWidth / 750) * 600, (that.data.deviceHeight / 1334) * 500);
    ctx.setFillStyle('white')
    //创建一个矩形
    ctx.fillRect(0, (that.data.deviceHeight / 1334) * 500, (that.data.deviceWidth / 750) * 600, (that.data.deviceHeight / 1334) * 500);
    //绘制图像到画布
    ctx.drawImage(imgUserPath, (that.data.deviceWidth / 750) * 30, (that.data.deviceHeight / 1334) * 560, (that.data.deviceWidth / 750) * 150, (that.data.deviceWidth / 750) * 150)

    //创建文字
    ctx.setFontSize((that.data.deviceWidth / 750) * 26)
    ctx.setFillStyle('#333333')
    //文案 x y
    ctx.fillText('AmHu', (that.data.deviceWidth / 750) * 210, (that.data.deviceHeight / 1334) * 590)

    ctx.setFontSize((that.data.deviceWidth / 750) * 22)
    ctx.setFillStyle('#666666')
    ctx.fillText('Web前端攻城狮', (that.data.deviceWidth / 750) * 210, (that.data.deviceHeight / 1334) * 655)

    ctx.setFontSize((that.data.deviceWidth / 750) * 22)
    ctx.setFillStyle('#999999')
    ctx.fillText('湖北武汉思高科技发展有限公司', (that.data.deviceWidth / 750) * 210, (that.data.deviceHeight / 1334) * 715)
   
    // ctx.fillRect(0, (that.data.deviceHeight / 1334) * 1000, (that.data.deviceWidth / 750) * 600, (that.data.deviceHeight / 1334) * 350);
    // //绘制图像到画布
    // ctx.drawImage(imgUserPath, (that.data.deviceWidth / 750) * 500, (that.data.deviceHeight / 1334) * 1030, (that.data.deviceWidth / 750) * 120, (that.data.deviceWidth / 750) * 120)

    ctx.fillRect(0, (that.data.deviceHeight / 1334) * 1000, (that.data.deviceWidth / 750) * 600, (that.data.deviceHeight / 1334) * 350);
    /*绘制文字*/
    ctx.setFontSize((that.data.deviceWidth / 750) * 22);
    ctx.setFillStyle('#666666');
    ctx.textAlign = "left";
    ctx.fillText('欢迎加入小鹿微名片名片组：', (that.data.deviceWidth / 750) * 30, (that.data.deviceHeight / 1334) * 800);

    ctx.setFontSize((that.data.deviceWidth / 750) * 24);
    ctx.setFillStyle('#666666')
    ctx.fillText(that.data.groupName, (that.data.deviceWidth / 750) * 30, (that.data.deviceHeight / 1334) * 880);

    ctx.setFontSize((that.data.deviceWidth / 750) * 22);
    ctx.setFillStyle('#666666')
    ctx.fillText('发起人：胡祥', (that.data.deviceWidth / 750) * 30, (that.data.deviceHeight / 1334) * 960);
     //绘制小程序码 x y width height
     ctx.drawImage(code, (that.data.deviceWidth / 750) * 380, (that.data.deviceHeight / 1334) * 800, (that.data.deviceWidth / 750) * 150, (that.data.deviceHeight / 1334) * 150);
    // ctx.setFontSize(18);
    // ctx.fillText(this.data.pro_price, 50, 400);
    // ctx.setFontSize(11);
    // ctx.setFillStyle('#666666');
    // ctx.fillText(this.data.poster_qrtext, 35, 420);
    // ctx.restore();
    //绘制图像到画布
    // ctx.drawImage(code, (that.data.deviceWidth / 750) * 470, (that.data.deviceHeight / 1334) * 540, (that.data.deviceWidth / 750) * 100, (that.data.deviceWidth / 750) * 100)
    //渲染
    ctx.draw(false, this.getTempFilePath)
  },
  //获取临时路径
  getTempFilePath: function () {
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 600,
      height: 750,
      destWidth: 1200, //2倍关系
      destHeight: 1500, //2倍关系
      canvasId: 'canvasposter',
      success: (res) => {
        this.saveImageToPhotosAlbum(res.tempFilePath)
      }
    })
  },
  //保存至相册
  saveImageToPhotosAlbum: function (imgUrl) {
    if (imgUrl) {
      wx.saveImageToPhotosAlbum({
        filePath: imgUrl,
        success: (res) => {
          wx.showModal({
            title: '提示',
            content: '图片已经保存到相册，发送至朋友圈即可邀请朋友进组',
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          drawing = false
        },
        fail: (err) => {
          wx.showToast({
            title: '保存失败',
            icon: 'none',
            duration: 2000
          })
          drawing = false
        }
      })
    } else {
      wx.showToast({
        title: '绘制中……',
        icon: 'loading',
        duration: 3000
      })
    }
  },
  /**
   * 点击设置按钮
   * 如果是群主跳转设置页面
   * 如果是普通成员跳转设置详情页面
   */
  toSetting: function () {
    console.log(this.type);
    console.log(this.data.groupId);

    if (this.data.is_leader == 1) {
      wx.navigateTo({
        url: `../settinggroup/settinggroup?news_id=${this.data.news_id}`,
        // url: '../settingdetails/settingdetails',
        success: function (res) {
          // success
        },
        fail: function () {
          // fail
        },
        complete: function () {
          // complete
        }
      })
    } else {
      wx.navigateTo({
        url: `../settingdetails/settingdetails?news_id=${this.data.news_id}`,
        success: function (res) {
          // success
        },
        fail: function () {
          // fail
        },
        complete: function () {
          // complete
        }
      })
    }
  },
  /**
   * 点击移除按钮
   */
  removeIteam() {
    this.setData({
      isRemove: !this.data.isRemove
    })
  },
  removeCard() {
    var that = this;
    wx.request({
      url: app.globalData.url + 'Group/isDel',
      data: {
        openid: wx.getStorageSync('openid'),
        news_id: that.data.news_id,
        card_id: that.data.query
      },
      method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        if (res.data.status === 1) {
          that.setData({
            searchData: res.data.data,
            searchBox: true,
            isSearch: false
          })
          console.log(that.data.searchData);

        } else if (res.data.status === 0) {
          wx.showToast({
            title: res.data.msg,
            // icon: 'success',
            duration: 2000
          })
        }
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
    this.setData({
      isRemove: !this.data.isRemove
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    var groupId = that.data.groupId;
    return {
      title: `欢迎加入小鹿微名片名片组: ${that.data.groupName}`,
      path: 'pages/groupdetails/groupdetails?news=' + groupId, //这里拼接需要携带的参数

      // imageUrl: 'https://ceshi.guirenpu.com/images/banner.png',
      success: function (res) {
        console.log("转发成功" + res);
      }
    }

  }
})